package test.solrcloud;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.NamedList;
import org.junit.Test;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.druid.DruidPlugin;

public class MoreLikeThis extends BaseSolrCloudTest {
	
	static String url = "jdbc:mysql://10.10.3.30/licai?characterEncoding=UTF-8";
	static String username = "kangrui";
	static String password = "kangrui123456";
	static int pageSize = 1000;
	
	@Test
	public void test1() {
		DruidPlugin dp = new DruidPlugin(url, username, password);
		ActiveRecordPlugin arp = new ActiveRecordPlugin(dp);
		arp.setDevMode(true);
		arp.setShowSql(true);
		dp.start();
		arp.start();
		
		List<Record> list = Db.find("select * from lc_article");
		List<SolrInputDocument> docs = new ArrayList<>();
		list.forEach(new Consumer<Record>() {
			@Override
			public void accept(Record t) {
				Integer id = t.getInt("id");
				Integer channel_id = t.getInt("channel_id");
				Integer click_count = t.getInt("click_count");
				Integer creater = t.getInt("creater");
				Integer updater = t.getInt("updater");
				Integer tag_id = t.getInt("channel_id");
				
				String author = t.getStr("author");
				
				String title = t.getStr("title");
				String text = delHTMLTag(t.getStr("text"));
				String keywords = t.getStr("keywords");
				String intro = t.getStr("intro");
				String description = t.getStr("description");
				
				Date ctime = t.getDate("ctime");
				
				SolrInputDocument doc = new SolrInputDocument();
				doc.addField("id", id);
				doc.addField("channel_id", channel_id);
				doc.addField("click_count", click_count);
				doc.addField("creater", creater);
				doc.addField("updater", updater);
				doc.addField("tag_id", tag_id);
				doc.addField("author", author);
				doc.addField("title", title);
				doc.addField("text", text);
				doc.addField("keywords", keywords);
				doc.addField("intro", intro);
				doc.addField("ctime", ctime);
				doc.addField("description", description);
				
				docs.add(doc);
			}
		});
		
		try {
			client.add("test1", docs);
			client.commit("test1");
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * morelikethis component
	 * 	  id，文档主键，或使用其他唯一键；
		  mlt 在查询时，打开/关闭 MoreLikeThisComponent 的布尔值。真|假 
		  fl，需要返回的字段
		  mtl.fl，根据哪些字段判断相似度
		  mlt.mindf，最小文档频率，所在文档的个数小于这个值的词将不用于相似判断
		  mlt.mintf，最小分词频率，在单个文档中出现频率小于这个值的词将不用于相似判断
		  mlt.count，返回相似文章个数
	 */
	@SuppressWarnings("rawtypes")
	@Test
	public void test2() {
		int id = 106;
		SolrQuery query = new SolrQuery();
		query.setQuery("id:" + id);
		query.setParam("mlt", true);
		query.setParam("mlt.fl", "title,text");
		query.setParam("mlt.count", "10");
		try {
			QueryResponse qr = client.query("test1", query);
			System.out.println(qr.getQTime());
			System.out.println(qr.getElapsedTime());
			NamedList<Object> nl = qr.getResponse();
			NamedList mlt = (NamedList) nl.get("moreLikeThis");
			SolrDocumentList docList = (SolrDocumentList)mlt.get(id+"");
			docList.forEach(new Consumer<SolrDocument>() {
				public void accept(SolrDocument t) {
					String id = t.get("id").toString();
					try {
						System.out.println(id + "--->" + client.getById("test1", id).get("title"));
					} catch (SolrServerException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					float score = (Float)t.get("score");
					System.out.println(score);
				};
			});
			
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void test3() {
		try {
			client.deleteByQuery("test1", "*:*");
			client.commit("test1");
		} catch (SolrServerException | IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 貌似morelikethis的handler不支持solrcloud
	 */
	@Test
	public void test4() {
		SolrQuery query = new SolrQuery();
		query.setRequestHandler("/mlt");
		query.setQuery("id:106");
		query.setParam("mlt.fl", "title,text");
		query.setStart(0);
		query.setRows(10);
		try {
			QueryResponse qr = client.query("test1", query);
			System.out.println(qr);
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String delHTMLTag(String htmlStr){ 
		if(htmlStr==null) return null;
        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式 
        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式 
        String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式 
         
        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE); 
        Matcher m_script=p_script.matcher(htmlStr); 
        htmlStr=m_script.replaceAll(""); //过滤script标签 
         
        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE); 
        Matcher m_style=p_style.matcher(htmlStr); 
        htmlStr=m_style.replaceAll(""); //过滤style标签 
         
        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE); 
        Matcher m_html=p_html.matcher(htmlStr); 
        htmlStr=m_html.replaceAll(""); //过滤html标签 

        return htmlStr.trim(); //返回文本字符串 
    } 

}
